package com.tts.service;

import com.tts.dto.BorrowStatisticsDTO;
import com.tts.dto.CategoryStatisticsDTO;
import com.tts.dto.PopularBookDTO;
import com.tts.entity.Book;
import com.tts.entity.BorrowRecord;
import com.tts.repository.BookRepository;
import com.tts.repository.BorrowRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StatisticsService {

    @Autowired
    private BorrowRecordRepository borrowRecordRepository;

    @Autowired
    private BookRepository bookRepository;

    public BorrowStatisticsDTO getBorrowStatistics(String startDate, String endDate) {
        LocalDateTime start = startDate != null ? 
            LocalDate.parse(startDate).atStartOfDay() : 
            LocalDateTime.now().minusDays(7).withHour(0).withMinute(0).withSecond(0);
        
        LocalDateTime end = endDate != null ? 
            LocalDate.parse(endDate).atTime(23, 59, 59) : 
            LocalDateTime.now();

        // 获取时间范围内的所有借阅记录
        List<BorrowRecord> records = borrowRecordRepository.findByBorrowTimeBetween(start, end);
        
        // 按日期分组统计
        Map<String, Integer> dailyCount = new HashMap<>();
        records.forEach(record -> {
            String date = record.getBorrowTime().format(DateTimeFormatter.ISO_DATE);
            dailyCount.merge(date, 1, Integer::sum);
        });
        
        BorrowStatisticsDTO dto = new BorrowStatisticsDTO();
        List<String> dates = new ArrayList<>(dailyCount.keySet());
        dates.sort(String::compareTo);
        dto.setDates(dates);
        dto.setCounts(dates.stream()
                .map(date -> dailyCount.getOrDefault(date, 0))
                .collect(Collectors.toList()));
        
        return dto;
    }

    public List<CategoryStatisticsDTO> getCategoryStatistics() {
        List<Book> books = bookRepository.findAll();
        Map<String, CategoryStatisticsDTO> categoryStats = new HashMap<>();
        
        books.forEach(book -> {
            categoryStats.computeIfAbsent(book.getCategory(), category -> {
                CategoryStatisticsDTO dto = new CategoryStatisticsDTO();
                dto.setCategory(category);
                dto.setTotalBooks(0);
                dto.setBorrowTimes(0);
                return dto;
            });
            
            CategoryStatisticsDTO dto = categoryStats.get(book.getCategory());
            dto.setTotalBooks(dto.getTotalBooks() + book.getTotalStock());
            dto.setBorrowTimes(dto.getBorrowTimes() + book.getBorrowTimes());
        });
        
        return new ArrayList<>(categoryStats.values());
    }

    public List<PopularBookDTO> getPopularBooks() {
        return bookRepository.findAll().stream()
                .map(book -> {
                    PopularBookDTO dto = new PopularBookDTO();
                    dto.setName(book.getName());
                    dto.setAuthor(book.getAuthor());
                    dto.setCategory(book.getCategory());
                    dto.setBorrowCount(book.getBorrowTimes());
                    return dto;
                })
                .sorted((a, b) -> b.getBorrowCount() - a.getBorrowCount())
                .limit(10)
                .collect(Collectors.toList());
    }
} 